package com.yueya.api.user;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.yueya.basic.dict.model.Dict;
import com.yueya.basic.token.model.Token;
import com.yueya.basic.user.model.User;
import com.yueya.basic.user.model.UserBase;
import com.yueya.common.constant.CodeConst;
import com.yueya.common.model.Resp;
import com.yueya.common.service.BaseService;
import com.yueya.common.util.Base64Util;
import com.yueya.common.util.Encrypt;
import com.yueya.common.util.UploadUtil;
import com.yueya.config.GlobalParam;

import net.sf.json.JSONObject;

public class IUserService extends BaseService {

	// 登陆，获取access-token
	public Resp login(JSONObject json) {
		Map<String, Object> data = new HashMap<String, Object>();
		if (containsKey(json, "loginname", "pwd")) {
			String loginName = json.getString("loginname");
			String pwd = json.getString("pwd");

			Record user = Db.findFirst("select u.* from t_user u where u.login_name ='" + loginName + "'");

			if (user != null) {
				String password = user.getStr("pwd");
				if (Encrypt.equalsByMD5(password, pwd)) {
					data.put("token", Token.dao.add(loginName));// 增加token
					resp.setCode(CodeConst.SUCCESS);
					resp.setData(data);
					resp.setMsg("登陆成功");
				} else {
					resp.setCode("20102");
					resp.setMsg("密码错误");
				}
			} else {
				resp.setCode("20103");
				resp.setMsg("用户不存在");
			}
		} else {
			resp.setCode("20101");
			resp.setMsg("JSON参数不合法");
		}
		return resp;
	}

	// 设置密码
	public Resp setPwd(JSONObject jo, String userId) {
		if (containsKey(jo, "pwd")) {
			int n = Db.update("update t_user set pwd=? where user_id=?", Encrypt.doStrByMD5(jo.getString("pwd")),
					userId);
			if (n != 0) {
				resp.setCode(CodeConst.SUCCESS);
			} else {
				resp.setCode("20104");
				resp.setMsg("设置密码不成功!");
			}

		} else {
			resp.setCode(CodeConst.JSONFORMAT_WRONG);
			resp.setMsg("JSON参数不合法");
		}

		return resp;
	}

	public Map<String, Object> getUser(JSONObject json) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> error = new HashMap<String, Object>();
		if (containsKey(json, "userid")) {
			String userId = json.getString("userid");
			Record user = Db.findFirst(
					"select u.user_id userid,u.user_name username,u.login_name loginname,u.pwd,u.last_login_time lastlogintime,u.create_time createtime "
							+ " ,ub.gender,ub.birthday,ub.address,ub.position,ub.phone,ub.email,ub.native,ub.nation,ub.join_time jointime,ub.avatar_path avatarpath,ub.remarks "
							+ " from t_user u left join t_user_base ub on ub.user_id = u.user_id where u.user_id ='"
							+ userId + "'");

			if (user != null) {
				// 头像路径
				if (StrKit.notBlank(user.getStr("avatarpath"))) {
					user.set("avatarpath", Dict.dao.getValue("attachment_url") + user.getStr("avatarpath"));
				}
				map.put("result", true);
				map.put("data", user);
			} else {
				map.put("result", false);
				error.put("errcode", "YY.ACCOUNT_ISNOTEXIST");
				error.put("errmsg", "用户不存在");
				map.put("error", error);
			}
		} else {
			map.put("result", false);
			error.put("errcode", "YY.INVALID_JSON_PARAM");
			error.put("errmsg", "JSON参数不合法");
			map.put("error", error);
		}

		return map;
	}

	public Map<String, Object> getUserList(JSONObject jo) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> error = new HashMap<String, Object>();

		if (containsKey(jo, "userid")) {
			String username = "";
			if (jo.containsKey("username")) {
				username = jo.getString("username");
			}

			String sql = "select u.user_name username, u.login_name tel ,left(u.user_pinyin,1) letter ,b.position  position "
					+ ",( CASE  b.avatar_path WHEN null THEN  b.avatar_path ELSE CONCAT('" + GlobalParam.getAttUrl()
					+ "' ,b.avatar_path )  END  ) avatarpath";
			sql += " from t_user u ,t_user_base  b where u.del_flag = '0' and u.user_id =b.user_id and u.user_id <> '0001'";
			if (StrKit.notBlank(username)) {
				sql += "  and u.user_name like '%" + username + "%'";
			}
			sql += " order by  u.user_pinyin asc ";
			List<User> userlist = User.dao.find(sql);

			map.put("result", true);
			map.put("userlist", userlist);

		} else {
			map.put("result", false);
			error.put("errcode", "INVALID_JSON_PARAM");
			error.put("errmsg", "JSON参数不合法");
			map.put("error", error);
		}

		return map;
	}

	public Resp uploadAvatar(JSONObject jo,String userId) {
		Map<String, Object> data = new HashMap<String, Object>();
		boolean bl = false;
		if (containsKey(jo,  "base64")) {
			String base64 = jo.getString("base64");
			// 保存头像图片
			String path = Base64Util.GenerateImage(base64);
			System.out.println("path:" + path);
			UserBase user = UserBase.dao.findByUserId(userId);
			if (user != null) {
				user.set("avatar_path", path);
				bl = user.update();
				if (bl) {
					resp.setCode(CodeConst.SUCCESS);
					
					data.put("path", UploadUtil.getUploadVisitUrl() + path);
					resp.setData(data);
					
				} else {
					resp.setCode("");
					resp.setMsg("操作失败");
				}

			} else {
				resp.setCode("");
				resp.setMsg("操作失败");
			}

		} else {
			resp.setCode(CodeConst.JSONFORMAT_WRONG);
			resp.setMsg("JSON参数不合法");
		}

		return resp;
	}
	
	
	public Resp uploadFile(JSONObject jo,String userId) {
		Map<String, Object> data = new HashMap<String, Object>();
		boolean bl = false;
		if (containsKey(jo,  "base64")) {
			String base64 = jo.getString("base64");
			// 保存头像图片
			String path = Base64Util.GenerateImage(base64);
			System.out.println("path:" + path);
			UserBase user = UserBase.dao.findByUserId(userId);
			if (user != null) {
				user.set("avatar_path", path);
				bl = user.update();
				if (bl) {
					resp.setCode(CodeConst.SUCCESS);
					
					data.put("path", UploadUtil.getUploadVisitUrl() + path);
					resp.setData(data);
					
				} else {
					resp.setCode("");
					resp.setMsg("操作失败");
				}

			} else {
				resp.setCode("");
				resp.setMsg("操作失败");
			}

		} else {
			resp.setCode(CodeConst.JSONFORMAT_WRONG);
			resp.setMsg("JSON参数不合法");
		}

		return resp;
	}
	

	public Record getUserByToken(String token) {
		String sql = "select u.*,du.dept_id from t_user u left join t_dept_user du on du.user_id = u.user_id where u.login_name = (select t.user_id from t_token t where t.token = ?)";
		return Db.findFirst(sql, token);
	}

}